<template>
  <div class="dept-management-container">
    <el-row :gutter="20">
      <!-- 左侧树形结构 (35%) -->
      <el-col :span="5">
        <div class="tree-section">
          <div class="tree-header">
            <h3>部门组织结构</h3>

          </div>
          <DeptTreeComponent />
        </div>
      </el-col>

      <!-- 右侧部门列表 (65%) -->
      <el-col :span="19">
        <div class="table-section">
          <div class="table-header">
            <h3>部门列表</h3>
            <el-button type="primary" @click="handleAddDept">
              <el-icon>
                <Plus />
              </el-icon>新增部门
            </el-button>
          </div>

          <el-table :data="deptList" border style="width: 100%">
            <!-- <el-table-column prop="Id" label="部门ID" width="180"></el-table-column> -->
            <el-table-column prop="Name" label="部门名称"></el-table-column>
            <el-table-column prop="CreatedBy" label="创建人"></el-table-column>
            <el-table-column prop="CreatedAt" label="创建时间"></el-table-column>

            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row.Id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="currentDept" label-width="120px">
        <el-form-item label="部门名称">
          <el-input v-model="currentDept.Name"></el-input>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="currentDept.ParentId" :options="treeData" :props="cascaderProps" placeholder="请选择上级部门"
            clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Plus } from '@element-plus/icons-vue';
import { VxeUI } from 'vxe-pc-ui'
import type { DeptMaster } from '@/viewModel/system.ts';
import { getDeptList, addDept, updateDept, deleteDept } from '@/api/system/dept';
import DeptTreeComponent from './DepTreeComponent.vue';

interface OriginalDeptItem {
  Id: string;
  Name: string;
  Children?: OriginalDeptItem[];
}
interface DeptResponse {
  Data: OriginalDeptItem[];
}

// 部门列表数据
const deptList = ref<DeptMaster[]>([]);
const dialogVisible = ref(false);
const isEditMode = ref(false);
const dialogTitle = ref('新增部门');
const currentDept = ref<DeptMaster>({
  Id: '',
  Name: '',
  ParentId: null,
  CreatedBy: '',
  CreatedAt: undefined
});

// 树形数据（用于级联选择器）
const treeData = ref<any[]>([]);

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true
};

// 获取部门列表
const fetchDepts = async () => {
  try {
    const res = await getDeptList();
    console.log('API响应:', res); // 打印完整响应

    if (res.Code === 200) {
    VxeUI.modal.message({
    id: 'myUniqueMsg',
    content: '查询成功',
    status: 'success'
  })
      deptList.value = res.Data;
    } else {
      ElMessage.warning(`查询成功但状态码异常: ${res.Code}`);
    }
  } catch (error) {
    console.error('API请求错误:', error);
    ElMessage.error('获取部门列表失败');
  }
};
// 刷新树形结构
const refreshTree = async () => {
  const res = await getDeptList() as DeptResponse;
  treeData.value = res.Data.map(item => ({
    id: item.Id,
    name: item.Name,
    children: item.Children || []
  }));
};

// 添加部门
const handleAddDept = () => {
  isEditMode.value = false;
  dialogTitle.value = '新增部门';
  currentDept.value = {
    Id: '',
    Name: '',
    ParentId: null,
    CreatedBy: '',
    CreatedAt: undefined
  };
  dialogVisible.value = true;
};

// 编辑部门
const handleEdit = (dept: DeptMaster) => {
  isEditMode.value = true;
  dialogTitle.value = '编辑部门';
  currentDept.value = JSON.parse(JSON.stringify(dept));
  dialogVisible.value = true;
};

// 删除部门
const handleDelete = (deptId: string) => {
  ElMessageBox.confirm('确定要删除该部门吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDept(deptId);
      ElMessage.success('删除成功');
      fetchDepts();
      refreshTree();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 提交表单
const submitForm = async () => {
  try {
    if (isEditMode.value) {
      await updateDept(currentDept.value);
      ElMessage.success('更新成功');
    } else {
      await addDept(currentDept.value);
      ElMessage.success('添加成功');
    }
    dialogVisible.value = false;
    fetchDepts();
    refreshTree();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 初始化加载数据
onMounted(() => {
  fetchDepts();
  refreshTree();
});
</script>

<style scoped>
.dept-management-container {
  padding: 20px;
  height: calc(100vh - 84px);
}

.tree-section,
.table-section {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  padding: 15px;
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tree-header,
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f2f5;
}

.tree-header h3,
.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.el-table {
  margin-top: 15px;
}

:deep(.el-tree) {
  height: calc(100% - 40px);
  overflow-y: auto;
}
</style>